import time
from datetime import datetime
import json

from influxdb_client import InfluxDBClient, Point, WritePrecision, BucketRetentionRules
from influxdb_client.client.write_api import SYNCHRONOUS, ASYNCHRONOUS

# You can generate an API token from the "API Tokens Tab" in the UI
bucket_token = "6ZrwxdzloJ__tCVgIgUwQRc8ADHcxzPFMrwbZsBVGvu87SuzVsSgMYq0Acc7nxPkzwm5RVjcYqVW96o_3CTL3w=="
admin_token = 'nGNZR26HVu6G3PRxDEzJnbIHXJsVx93whXEb6JXQWepJQ5a5qtbu6GKQsu8qm6N7hwZiwwcFd-g1VThMxLUCFg=='
org = "ILS_MON"
bucket = "ILS_MON"

with InfluxDBClient(url="http://127.0.0.1:8086", token=admin_token, org=org) as client:
    write_api = client.write_api(write_options=SYNCHRONOUS)

    data = {
        'measurement': 'ils_id',
        'time': time.time_ns(),
        "fields": {
            "mon1|CL DDM|val": 0.02,
            "mon1|CL DDM|stat": True,
            "mon1|CL SDM|val": 40.3,
            "mon1|CL SDM|stat": True,
        },
        "tags": {
            "alarm_mark": "begin",
            "servicing": 'True'
        }
    }
    # try:
    #     write_api.write(bucket=bucket, org=org, record=data)
    # except BaseException:
    #     # retention_rule = BucketRetentionRules(every_seconds=3600, shard_group_duration_seconds=3600)
    #     # client.buckets_api().create_bucket(bucket_name=bucket, org=org, retention_rules=retention_rule)
    #     client.buckets_api().create_bucket(bucket_name=bucket, org=org)
    #     write_api.write(bucket=bucket, org=org, record=data)

    # bucketname = client.buckets_api().find_bucket_by_name(bucket)
    # retention_rule = BucketRetentionRules(every_seconds=3601, shard_group_duration_seconds=3600)
    # bucketname.retention_rules = [retention_rule]
    # client.buckets_api().update_bucket(bucketname)

    query = 'from(bucket: "{0}") |> range(start: 0) ' \
            '|>filter(fn: (r) => r["alarm_mark"] == "begin" and (r["_field"]=="mon1|CL DDM|val" or r["_field"]=="mon1|CL DDM|stat"))' \
            '|>keep(columns: ["_time", "_field", "_value"])' \
            ''.format(bucket)
    # print(query)
    tables = client.query_api().query(query, org=org)

    res = {}
    for table in tables:
        for record in table.records:
            if res.get(record.get_time().timestamp()) is None:
                res[record.get_time().timestamp()] = {record.get_field(): record.get_value()}
            else:
                res[record.get_time().timestamp()][record.get_field()] = record.get_value()
    print(res)



